package ArraySeries;

public class BinarySearchSolution_704_2 {
    public int search(int[] nums, int target) {
        //排除特殊情况
        if (target < nums[0] || target > nums[nums.length - 1]) {
            return -1;
        }
        // 假设左闭右闭
        //二分查找法，设置左右边界
        int left = 0;
        int right = nums.length - 1;

        // 外循环
        while (left <= right) {
            // 防止溢出
            int mid = left + ((right - left) / 2);
            // target在右边区域
            if (target == nums[mid]) {
                return mid;
            } else if (target > nums[mid]) {
                left = mid + 1;
            }
            // target在左边区域
            else if (target < nums[mid]) {
                right = mid - 1;
            }
        }
        // 未找到target
        return -1;
    }
}
